package com.antler.smt.admin.service.impl;

import com.antler.smt.admin.mapper.MemberEntityMapper;
import com.antler.smt.admin.mapper.OrderInfoMapper;
import com.antler.smt.admin.mapper.SupplierEntityMapper;
import com.antler.smt.admin.mapper.SupplierInfoMapper;
import com.antler.smt.admin.utils.ShiroUtils;
import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.entity.MemberEntity;
import com.antler.smt.entity.SupplierEntity;
import com.antler.smt.entity.UserEntity;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.request.admin.GetSupplierListReq;
import com.antler.smt.request.base.BasePageReq;
import com.antler.smt.response.admin.GetSupplierListResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.service.admin.SupplierService;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.LogUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 *  服务商接口实现
 *
 * @author zhangyi
 * @date 2018/3/26 14:49
 */
@Service
public class SupplierServiceImpl implements SupplierService {

    /**
     * 日志
     */
    private static Logger log = LogUtil.get();

    @Autowired
    private SupplierInfoMapper supplierInfoMapper;

    @Autowired
    private SupplierEntityMapper supplierEntityMapper;

    @Autowired
    private MemberEntityMapper memberEntityMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    /**
     * 获取服务商列表
     *
     * @param request 请求实体
     * @return
     */
    @Override
    public Result<Page<GetSupplierListResp>> getSupplierList(GetSupplierListReq request) {
        PageHelper.startPage(request.getPageCurrent(), request.getPageSize());

        Page<GetSupplierListResp> listSupplierInfo = supplierInfoMapper.selectSupplierAccountList();

        PageInfo<GetSupplierListResp> supplierListPageInfo = null;
        if (listSupplierInfo != null) {
             supplierListPageInfo  = new PageInfo(listSupplierInfo);
        }

        Result result = new Result(supplierListPageInfo);
        return result;
    }

    /**
     * 获取服务商详情
     *
     * @param id
     * @return
     */
    @Override
    public Result<SupplierEntity> getSupplierInfo(Long id) {
        Result result = null;

        SupplierEntity supplierEntity = supplierEntityMapper.selectByPrimaryKey(id);

        result = new Result(supplierEntity);

        return result;
    }

    /**
     * 获取服务商入驻审核状态列表
     *
     * @param request
     * @return
     */
    @Override
    public Result<Page<GetSupplierListResp>> getSupplierSettledList(GetSupplierListReq request) {
        PageHelper.startPage(request.getPageCurrent(), request.getPageSize());
        Page<GetSupplierListResp> listSupplierSettled = supplierInfoMapper.listSupplierSettled(request);
        for(int i = 0; i < listSupplierSettled.size(); i++){
            MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(listSupplierSettled.get(i).getMemberId());
            if(memberEntity != null) {
                listSupplierSettled.get(i).setStatus(memberEntity.getStatus());
                listSupplierSettled.get(i).setMobile(memberEntity.getMobile());
                listSupplierSettled.get(i).setNickName(memberEntity.getNickName());
                listSupplierSettled.get(i).setEmail(memberEntity.getEmail());
            }
        }

        PageInfo<GetSupplierListResp> supplierSettledListPageInfo = null;
        if (listSupplierSettled != null) {
            supplierSettledListPageInfo = new PageInfo(listSupplierSettled);
        }
        Result result = new Result(supplierSettledListPageInfo);
        return result;
    }

    /**
     * 修改服务商入驻审核结果
     *
     * @param id
     * @param settledAuditResult
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> updateSupplierSettled(Long id, Integer settledAuditResult) {
        Result result = null;

        SupplierEntity supplierEntity = new SupplierEntity();

        //添加主键
        supplierEntity.setId(id);

        //入住申请状态
        supplierEntity.setSettledAuditResult(settledAuditResult);

        //审核入驻时间
        supplierEntity.setSettledAuditTime(DateUtil.stampToDate(System.currentTimeMillis()));

        UserEntity userEntity = ShiroUtils.getUserEntity();
        if(userEntity!=null){
            //获取审核入驻项目专员
            supplierEntity.setSettledAuditUserId(userEntity.getId());
        }

        int i = supplierEntityMapper.updateByPrimaryKeySelective(supplierEntity);

        if(0 == i){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        return result;
    }

    /**
     *  优质加工厂审核
     *
     * @param id
     * @param auditResult
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> excellentAudit(Long id,Integer auditResult) {
        Result result = null;

        //服务商实体
        SupplierEntity supplierEntity = new SupplierEntity();

        //设置服务商id
        supplierEntity.setId(id);

        //设置申请状态
        supplierEntity.setAuditResult(auditResult);

        //设置认证时间
        supplierEntity.setAuditTime(DateUtil.stampToDate(System.currentTimeMillis()));

        UserEntity userEntity = ShiroUtils.getUserEntity();
        if(userEntity!=null){
            //获取审核入驻项目专员
            supplierEntity.setAuditUserId(userEntity.getId());
        }

        //更新认证状态
        int i = supplierEntityMapper.updateByPrimaryKeySelective(supplierEntity);

        if(0 == i){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        return result;
    }

    /**
     *  优质服务商待审核列表
     *
     * @param auditResult 审核状态
     * @return
     */
    @Override
    public Result<Page<GetSupplierListResp>> getExcellentSupplierList(Integer auditResult,GetSupplierListReq request) {
        Result result = null;

        PageHelper.startPage(request.getPageCurrent(), request.getPageSize());

        //服务商实体
        GetSupplierListReq getSupplierListReq = new GetSupplierListReq();

        //审核状态
        getSupplierListReq.setAuditResult(auditResult);


        Page<GetSupplierListResp> listSupplierInfo = supplierInfoMapper.listSupplierInfo(getSupplierListReq);

        for (int i = 0; i < listSupplierInfo.size(); i++){

            Map<String, Object> someSupplieInfo = getSomeSupplieInfo(listSupplierInfo.get(i).getId());

            listSupplierInfo.get(i).setEmail((String) someSupplieInfo.get("email"));
            listSupplierInfo.get(i).setMobile((String) someSupplieInfo.get("mobile"));
            listSupplierInfo.get(i).setOrderNumber((Integer) someSupplieInfo.get("orderNumber"));

                MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(listSupplierInfo.get(i).getMemberId());
                if(memberEntity != null) {
                    listSupplierInfo.get(i).setStatus(memberEntity.getStatus());
                }
        }

        PageInfo<GetSupplierListResp> supplierListPageInfo = null;
        if (listSupplierInfo != null) {
            supplierListPageInfo = new PageInfo(listSupplierInfo);
        }
        result = new Result(supplierListPageInfo);

        return result;
    }

    /**
     *  获取服务商入驻已审核列表（通过，和未通过）
     *
     * @return
     */
    @Override
    public Result<Page<GetSupplierListResp>> selectEndSetted(BasePageReq basePageReq) {
        Result result = null;

        PageHelper.startPage(basePageReq.getPageCurrent(), basePageReq.getPageSize());

        Page<GetSupplierListResp> listSupplierInfo = supplierInfoMapper.selectEndSetted();

        for (int i = 0; i < listSupplierInfo.size(); i++){

            Map<String, Object> someSupplieInfo = getSomeSupplieInfo(listSupplierInfo.get(i).getId());

            listSupplierInfo.get(i).setEmail((String) someSupplieInfo.get("email"));
            listSupplierInfo.get(i).setMobile((String) someSupplieInfo.get("mobile"));
            listSupplierInfo.get(i).setOrderNumber((Integer) someSupplieInfo.get("orderNumber"));

            MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(listSupplierInfo.get(i).getMemberId());
            if(memberEntity != null) {
                listSupplierInfo.get(i).setStatus(memberEntity.getStatus());
            }
        }

        PageInfo<GetSupplierListResp> supplierListPageInfo = null;
        if (listSupplierInfo != null) {
            supplierListPageInfo = new PageInfo(listSupplierInfo);
        }
        result = new Result(supplierListPageInfo);

        return result;
    }

    /**
     *  获取优质服务商已审核列表（通过，和未通过）
     *
     * @return
     */
    @Override
    public Result<Page<GetSupplierListResp>> selectEndExcellentAudit(BasePageReq basePageReq) {
        Result result = null;

        PageHelper.startPage(basePageReq.getPageCurrent(), basePageReq.getPageSize());

        Page<GetSupplierListResp> listSupplierInfo = supplierInfoMapper.selectEndExcellentAudit();

        for (int i = 0; i < listSupplierInfo.size(); i++){

            Map<String, Object> someSupplieInfo = getSomeSupplieInfo(listSupplierInfo.get(i).getId());

            listSupplierInfo.get(i).setEmail((String) someSupplieInfo.get("email"));
            listSupplierInfo.get(i).setMobile((String) someSupplieInfo.get("mobile"));
            listSupplierInfo.get(i).setOrderNumber((Integer) someSupplieInfo.get("orderNumber"));
            MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(listSupplierInfo.get(i).getMemberId());
            if(memberEntity != null) {
                listSupplierInfo.get(i).setStatus(memberEntity.getStatus());
            }

        }

        PageInfo<GetSupplierListResp> supplierListPageInfo = null;
        if (listSupplierInfo != null) {
            supplierListPageInfo = new PageInfo(listSupplierInfo);
        }
        result = new Result(supplierListPageInfo);

        return result;
    }

    /**
     *  服务商信息修改
     *
     * @param supplierId 服务商id
     * @param req 请求服务商实体
     * @return
     */
    @Override
    public Result<ResultCodeEnum> editSupplierInfo(Long supplierId ,GetSupplierListReq req) {
        Result result = null;
        //创建服务商实体
        SupplierEntity supplierEntity = new SupplierEntity();

        //插入id
        supplierEntity.setId(supplierId);

        //插入星级
        supplierEntity.setGrade(req.getGrade());

        //插入规模
        supplierEntity.setScale(req.getScale());

        int i = supplierEntityMapper.updateByPrimaryKeySelective(supplierEntity);

        if(0 == i){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }

        return result;
    }

    /**
     * 冻结服务商账户
     *
     * @param supplierId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> freezeSupplier(Long supplierId,Integer status) {
        Result result = null;
        MemberEntity memberEntity = new MemberEntity();

        SupplierEntity supplierEntity = supplierEntityMapper.selectByPrimaryKey(supplierId);

            //插入主键id
            memberEntity.setId(supplierEntity.getMemberId());
            //插入状态
            memberEntity.setStatus(status);
            int j = memberEntityMapper.updateByPrimaryKeySelective(memberEntity);
            result = (0 == j ? new Result<>(ResultCodeEnum.APPEND_DATA_ERROR):new Result<>(ResultCodeEnum.OPERATION_SUCCESS));
        return result;
    }

    /**
     * 填充服务商表中剩余字段（邮箱，手机号，订单编号）
     *
     * @param supplierId 采购商id
     * @return
     */
    private Map<String,Object> getSomeSupplieInfo(Long supplierId){


        SupplierEntity supplierEntity = supplierEntityMapper.selectByPrimaryKey(supplierId);
        //获取会员实体
        MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(supplierEntity.getMemberId());

        //返回Map
        Map<String,Object> map = new HashMap<>();

        map.put("email",memberEntity.getEmail());
        map.put("mobile",memberEntity.getMobile());

        int orderNumber = orderInfoMapper.selectOrderBySupplierId(supplierId);

        map.put("orderNumber",orderNumber);

        return map;
    }

}
